package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;
	@Autowired
	private UserAccountMapper userAccountMapper;
	@Autowired
	private UserAccountService userAccountService;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void rechargePaySuccess(String orderNo) {
		RechargeInfo rechargeInfo = this.getRechargeInfo(orderNo);
		if (null == rechargeInfo||rechargeInfo.getRechargeStatus().equals(SystemConstant.ORDER_STATUS_PAID)){
			return;
		}
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
		this.updateById(rechargeInfo);

		userAccountMapper.updateAvailableAmount(rechargeInfo.getUserId(),rechargeInfo.getRechargeAmount());

		userAccountService.addUserAccountDetail(rechargeInfo.getUserId(),"充值",SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,rechargeInfo.getRechargeAmount(),orderNo);




	}

	@Override
	public String submitRecharge(RechargeInfoVo rechargeInfoVo, Long userId) {

		RechargeInfo rechargeInfo = new RechargeInfo();
		rechargeInfo.setUserId(userId);
		String orderNo = UUID.randomUUID().toString().replace("-", "");
		rechargeInfo.setOrderNo(orderNo);
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
		rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
		rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
		rechargeInfoMapper.insert(rechargeInfo);

		return orderNo;
	}

	@Override
	public RechargeInfo getRechargeInfo(String orderNo) {
		return rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
	}
}
